// pages/sign/sign.js
Page({

    /**
     * 页面的初始数据
     */

    data: {
        today: new Date().getTime(),
        signList: [],
        todayHasSigned: false,
        showSignBanner: false,
        userExamId: null,
        isInIsolation: 0,
        touchedCase: 0,
        selectedImages: [],
        healthCode: -1,
        position: "",
        heat: null,
        uploadedImages: []
    },
    showShowSignBanner() {
        this.setData({
            showSignBanner: true
        })
        this.getHealthCode(getApp().userinfo.id);
    },
    closeShowSignBanner() {
        this.setData({
            showSignBanner: false
        })

    },
    inputPosition(e) {
        this.setData({
            position: e.detail.value
        })
    },
    inputHeat(e) {
        this.setData({
            heat: e.detail.value
        })
    },
    selectImage() {
        let that = this;
        wx.chooseImage({
            count: 6 - this.data.selectedImages.length,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success: (result) => {
                let selectedImages = that.data.selectedImages;
                for (let index in result.tempFilePaths) {
                    let selectedImage = {};
                    let src = result.tempFilePaths[index];
                    selectedImage.src = src;
                    if (result.tempFiles.length > index) {
                        selectedImage.imgObj = result.tempFiles[index];
                    }
                    if (!that.imageHasSelected(src)) {
                        selectedImages.push(selectedImage)
                    }


                }
                that.setData({
                    selectedImages: selectedImages
                })

            },
            fail: () => {
            },
            complete: () => {
            }
        });
    },
    imageHasSelected(src) {
        for (let index in this.data.selectedImages) {
            let img = this.data.selectedImages[index];
            if (img.src == src) {
                return true;
            }

        }
        return false;
    },
    canccelSelectImage(e) {
        let that = this;
        wx.showModal({
            title: '提示',
            content: '是否删除该照片？',
            showCancel: true,
            cancelText: '取消',
            cancelColor: '#000000',
            confirmText: '确定',
            confirmColor: '#3CC51F',
            success: (result) => {
                if (result.confirm) {
                    let willBeCancelImg = that.data.selectedImages[e.currentTarget.dataset.index];
                    let newImages = [];
                    for (let index in that.data.selectedImages) {
                        let img = that.data.selectedImages[index];
                        if (img.src != willBeCancelImg.src) {
                            newImages.push(img);
                        }

                    }
                    that.setData({
                        selectedImages: newImages
                    })
                }
            },
            fail: () => {
            },
            complete: () => {
            }
        });

    },
    uploadPhotos(callback) {
        this.data.uploadedImages = [];
        wx.showLoading({
            title: "图片上传中···",
            mask: true
        });
        let loadingIsShow = true;
        let that = this;
        for (let index in that.data.selectedImages) {
            let filePath = that.data.selectedImages[index].src;
            wx.uploadFile({
                url: wx.surls.upload.upload.url,
                filePath: filePath,
                name: "images",
                // formData: {},
                success: (result) => {
                    console.log(result);
                    that.data.uploadedImages.push({
                        index: index,
                        file: result.data
                    })
                    if (loadingIsShow && that.data.uploadedImages.length >= that.data.selectedImages.length) {
                        wx.hideLoading();
                        that.data.uploadedImages.sort(function (a, b) {
                            return a.index < b.index;
                        })
                        console.log(that.data.uploadedImages);
                        callback();
                    }
                },
                fail: (err) => {
                    console.log(err);
                    if (loadingIsShow) {
                        wx.hideLoading();
                        loadingIsShow = false;
                        wx.su.toast("上传图片失败，请检查网络后重试");
                    }
                },
                complete: () => {

                }
            });

        }

    },
    reGetHealthCode() {
        this.getHealthCode(getApp().userinfo.id)
    },
    getHealthCode(userId) {
        let that = this;
        wx.scommon.rget(wx.surls.sign.healthCode.add(userId), function (res) {
            that.setData({
                healthCode: res.data
            })
        }, function () {
            that.setData({
                healthCode: -2
            })
        })
    },
    onLoad: function (options) {
        this.data.userExamId = options.userExamId;
        this.getTodayHasSign();
        this.getSignListIn14Days();
        
    },
    getSignListIn14Days() {
        let that = this;
        wx.scommon.rget(wx.surls.sign.signList.add(this.data.userExamId), function (res) {
            that.setData({
                signList: res.data
            })
        })
    },
    getTodayHasSign() {
        let that = this;
        wx.scommon.rget(wx.surls.sign.today.add(this.data.userExamId), function (res) {
            that.setData({
                todayHasSigned: res.data
            })
            if (!res.data) {
                that.showShowSignBanner();
            }
        })
    },
    commitSign() {
        let signData = {};
        if (!this.data.userExamId) {
            wx.su.toast("数据异常")
            return false;
        }
        signData.user_exam_id = this.data.userExamId;
        if (this.data.healthCode == -1 || this.data.healthCode == -2) {
            wx.su.toast("请获取健康码状态")
            return false;
        }
        signData.health_code = this.data.healthCode;

        if (!this.data.selectedImages || this.data.selectedImages.length < 1) {
            wx.su.toast("请上传行程码截图")
            return false;
        }
        if (!this.data.heat) {
            wx.su.toast("请输入当前体温")
            return false;
        }
        signData.heat = this.data.heat;
        if (!this.data.position) {
            wx.su.toast("请输入当前所在地")
            return false;
        }
        signData.position = this.data.position;
        signData.is_in_isolation = this.data.isInIsolation;
        signData.touched_case = this.data.touchedCase;
        let that = this;
        this.uploadPhotos(function () {
            signData.journey = JSON.stringify(that.data.uploadedImages);
            wx.scommon.rpost(wx.surls.sign.sign, signData, function (res) {

                wx.su.toast("打开成功")
                that.closeShowSignBanner();
                that.getSignListIn14Days();
                that.setData({
                    todayHasSigned: true
                })
            }, function () {
                wx.su.toast("提交失败，请检查网络后重试");
            })
        })

        // journey
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    }
    ,

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    }
    ,

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    }
    ,

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    }
    ,

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    }
    ,

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    }
    ,

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})
